package com.pb.metadata.controller;

import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.metadata.service.FieldManagementService;
import com.pb.infra.oth.util.ImportExcel;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.util.Constant;
import com.pb.infra.oth.util.SysLog;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 字段管理
 * @author liaohaoyuan
 * @date 20210301
 */
@Slf4j
@RestController
@RequestMapping("v1/metadata/fieldManagement")
public class FieldManagementController {

    /**
     * 业务逻辑对象
     */
    @Resource
    private FieldManagementService fieldManagementService;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * 日志操作表
     */
    private static final String TABLE_NAME = "param_column";

    /**
     * 日志操作功能名
     */
    private static final String OPERATION_MENU = "字段管理";

    /**
     * 查询字段分页数据
     * @param map 查询参数
     * @param page 页码
     * @return Result 返回数据
     */
    @GetMapping("select")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result select(@RequestParam Map<String, Object> map, Page page) {
        return fieldManagementService.select(map, page);
    }

    /**
     * 字段管理新建数据
     *
     * @param paramMap 请求参数
     * @return Result 返回数据
     */
    @PostMapping("insert")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.ADD, menuName = OPERATION_MENU)
    public Result insert(@RequestBody Map<String, Object> paramMap, HttpServletRequest request) {
        try {
            Result insert = fieldManagementService.insert(paramMap, request);
            return insert;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(Constant.EXIST, Constant.INSERT_ERROR_MSG);
        }
    }

    /**
     * 修改字段
     *
     * @param paramMap 请求参数
     * @return Result 返回数据
     */
    @PostMapping("update")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.MOD, menuName = OPERATION_MENU)
    public Result update(@RequestBody Map<String, Object> paramMap, HttpServletRequest request){
        try {
            SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
            paramMap.put("updateTime",format.format(new Date()));
            Result insert = fieldManagementService.update(paramMap, request);
            return insert;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(Constant.EXIST, Constant.UPDATE_ERROR_MSG);
        }
    }

    /**
     * 查询数据库用户类型下拉列表
     *
     * @return Result 返回数据
     */
    @GetMapping("getDatabaseUserList")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result getDatabaseUserList() {
        return fieldManagementService.getDatabaseUserList();
    }

    /**
     * 查询字段类型码值
     *
     * @return Result 返回数据
     */
    @GetMapping("getColumnTypeList")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result getColumnTypeList() {
        return fieldManagementService.getColumnTypeList();
    }

    /**
     * 查询字段用途码值
     *
     * @return Result 返回数据
     */
    @GetMapping("getColumnUseList")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.QUERY, menuName = OPERATION_MENU)
    public Result getColumnUseList() {
        return fieldManagementService.getColumnUseList();
    }

    /**
     * 删除字段
     *
     * @param paramMap 请求参数
     * @return Result 返回数据
     */
    @PostMapping("delete")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.DEL, menuName = OPERATION_MENU)
    public Result delete(@RequestBody List<String> paramMap) {
        fieldManagementService.delete(paramMap);
        return Result.OK_EMPTY;
    }

    /**
     * 启用停用字段
     * @param paramMap 请求参数
     * @return Result 返回数据
     */
    @PostMapping("startOrStop")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.MOD, menuName = OPERATION_MENU)
    public Result startOrStop(@RequestBody List<Map<String,Object>> paramMap){
        fieldManagementService.startOrStop(paramMap);
        return Result.OK_EMPTY;
    }

    /**
     * 锁定码表相关信息
     *
     * @param paramMap 请求参数
     * @return Result 返回数据
     */
    @PostMapping("lockedBatch")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.MOD, menuName = OPERATION_MENU)
    public Result lockedDate(@RequestBody List<String> paramMap) {
        fieldManagementService.lockedDate(paramMap);
        return Result.OK_EMPTY;
    }

    /**
     * 提交码表相关信息
     *
     * @param paramMap 请求参数
     * @return Result 返回数据
     */
    @PostMapping("freeBatch")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.MOD, menuName = OPERATION_MENU)
    public Result freeDate(@RequestBody List<String> paramMap) {
        fieldManagementService.freeDate(paramMap);
        return Result.OK_EMPTY;
    }

    /**
     * 导出
     * @param paramMap 请求参数
     * @return Map 返回数据
     */
    @PostMapping("/exportColumnExcel")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.EXP, menuName = OPERATION_MENU)
    public Map<String, Object> exportColumnExcel(@RequestBody  Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        paramMap.put("userId", userId);
        List<Map<String,Object>> list=fieldManagementService.selectList(paramMap);
        String databaseUserString = fieldManagementService.getDatabaseUserStr();
        paramMap.clear();
        String[][] strArr={{"数据库用户",  "字段名称", "字段描述", "字段类型", "字段长度", "字段小数", "字段用途", "有效标识", "排序标识", "锁定标识", "备注"}};
        String[][] nameArr={{"databaseUser","columnName","cnName","columnTypeDesc","dataLength","dataScale","columnUseDesc","activeDesc","orderFlag","recordStsDesc","remarks"}};
        String[][] dataType = {{"STRING","STRING","STRING","STRING","NUMBER","NUMBER","STRING","STRING","STRING","STRING","STRING"}};
        String[][] comments={{databaseUserString,  "首位必须是字母,可包含下划线、数字", "", "字段类型：字符串，数字，日期", "", "", "字段用途：维度，量度，其它", "有效标识：启用，停用", "","锁定标识：空闲，锁定，打包",""}};
        Object[] obj={list};
        String[] jobBookName={"字段管理"};
        paramMap.put("jobBookName",jobBookName);
        paramMap.put("title",strArr);
        paramMap.put("order",nameArr);
        paramMap.put("comments",comments);
        paramMap.put("token",token);
        paramMap.put("data",obj);
        paramMap.put("dataType",dataType);//数据类型 有NUMBER,STRING,DOUBLE三种数据类型
        paramMap.put("fileName","字段管理");
        return  paramMap;
    }

    /**
     * 导入
     * 加入@ImportExcel注解完成数据的校验过程
     * @param paramMap 获取校验完成的数据（data），及提示信息(msg)和状态(caode)，code=1表示正确，code=-1表示数据不正确
     * @return Result 返回数据
     */
    @PostMapping("importExcel")
    @SysLog(tableName = TABLE_NAME, action = Constant.ACTION_NAME.IMP, menuName = OPERATION_MENU)
    public Result importExcel(@ImportExcel() Map<String,Object> paramMap){
        try {
            Integer code= (Integer) paramMap.get("code");//得到校验结果
            //code=1标识数据正确
            if (code==1){
                List<List<Map<String,Object>>> data = ( List<List<Map<String,Object>>>) paramMap.get("data"); //得到Excel中的所有数据
                String msg=fieldManagementService.importExcel(data);
                if (!"".equals(msg)){
                    paramMap.put("msg",msg+paramMap.get("msg"));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            paramMap.put("msg","导入遇到异常请联系管理员");
        }
        paramMap.remove("data");
        return Result.ok(paramMap);
    }

}
